<template>
  <div id="user">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>溯源管理</el-breadcrumb-item>
      <el-breadcrumb-item>病害列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!--搜索框-->
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input
              v-model="searchForm.symptomName"
              placeholder="病害名称"
              clearable>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getSymptomList">搜索</el-button>
          <el-button type="primary" @click="dialogFormVisible = true" v-if="hasAuth('trace:symptom:save')">新增</el-button>
          <el-popconfirm title="确定要删除这些记录吗？" @confirm="delHandle(null)" style="margin-left: 10px;" v-if="hasAuth('trace:symptom:delete')">
            <el-button type="danger" slot="reference" :disabled="delBtnStu">批量删除</el-button>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!--列表-->
      <el-table
          ref="multipleTable"
          border
          stripe
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="symptomName"
            label="病害名称">
        </el-table-column>
        <el-table-column
            prop="symptomDistribute"
            label="病害分布及危害">
        </el-table-column>
        <el-table-column
            prop="symptomCause"
            label="病源">
        </el-table-column>
        <el-table-column
            prop="symptomRule"
            label="发生规律">
        </el-table-column>
        <el-table-column
            prop="symptomPrevent"
            label="防治方法">
        </el-table-column>
        <el-table-column
            prop="symptomPrevent"
            label="图片展示">
          <template slot-scope="scope">
            <el-popover placement="top-start" title="" trigger="hover">
              <img :src="scope.row.symptomPicture" alt="" style="width: 150px;height: 150px">
              <img slot="reference" :src="scope.row.symptomPicture" style="width: 30px;height: 30px">
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间">
        </el-table-column>
        <el-table-column
            width="260px"
            label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="editHandle(scope.row.symptomId)" v-if="hasAuth('trace:plot:update')">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" @click="editPictureHandle(scope.row.symptomId)" v-if="hasAuth('trace:plot:update')">修改图片</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.symptomId)" v-if="hasAuth('trace:plot:delete')">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--页码-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <el-dialog title="病害信息" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="editForm" :rules="editFormRules" ref="editForm">
          <el-form-item label="病害名称" prop="symptomName" label-width="100px">
            <el-input v-model="editForm.symptomName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="病害分布危害" prop="symptomDistribute" label-width="100px">
            <el-input type="textarea" autosize v-model="editForm.symptomDistribute" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="病源" prop="symptomCause" label-width="100px">
            <el-input type="textarea" autosize v-model="editForm.symptomCause" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="发生规律" prop="symptomRule" label-width="100px">
            <el-input type="textarea" autosize v-model="editForm.symptomRule" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="防治方法" prop="symptomPrevent" label-width="100px">
            <el-input type="textarea" autosize v-model="editForm.symptomPrevent" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('editForm')">取 消</el-button>
          <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="病害图片" :visible.sync="pictureFormVisible" width="600px">
        <el-upload
            style="display: inline-block"
            class="upload-demo"
            ref="upload"
            action=""
            :multiple="false"
            :on-remove="handleRemove"
            :on-progress="progressA"
            :http-request="customUpload"
            :file-list="fileList"
            :show-file-list="true"
            multiple
            drag
            :auto-upload="true">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text" style="vertical-align: middle;"><p>将文件拖到此处，或<em>点击上传</em></p></div>
        </el-upload>


<!--        <div slot="footer" class="dialog-footer">-->
<!--          <el-button @click="resetForm('editForm')">取 消</el-button>-->
<!--          <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>-->
<!--        </div>-->
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import * as SparkMD5 from "core-js";

export default {
  name: "Forest",
  data() {
    return {
      fileList: [],
      md5: '',
      fileTable: [{
        fileName: '文件名',
        speed: '进度'
      }],
      searchForm: {
        symptomName: ''
      },
      editForm: {
      },
      editFormRules: {
        symptomName: [
          {required: true, message: '请输入树种名称', trigger: 'blur'}
        ]
      },
      current: 1,
      total: 0,
      size: 10,
      dialogFormVisible: false,
      pictureFormVisible: false,
      tableData: [],
      multipleSelection: [],
      delBtnStu: true,
      roleDialogFormVisible: false,
      roleForm: {
      },
      defaultProps: {
        children: 'children',
        label: 'chineseName'
      },
      roleTreeData:  [],
      treeCheckedKeys: [],
    }
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    getSymptomList() {
      this.$http.get('/trace/symptom/list', {
        params: {
          symptomName: this.searchForm.symptomName,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data.data.records
        console.log(this.tableData)
        this.current = res.data.data.current
        this.size = res.data.data.size
        this.total = res.data.data.total
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.getSymptomList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getSymptomList()
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post('/trace/symptom/' + (this.editForm.symptomId? "update" : "save") ,this.editForm)
              .then(res => {
                console.log(res.data)
                this.resetForm(formName)
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getSymptomList()
                  }
                });
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandle(id) {
      console.log(id)
      this.$http.get("/trace/symptom/info/" + id).then(res => {
        this.editForm = res.data.data
        this.dialogFormVisible = true
      })
    },
    editPictureHandle(id) {
      console.log(id)
      this.$http.get("/trace/symptom/info/" + id).then(res => {
        this.editForm = res.data.data
        this.pictureFormVisible = true
      })
    },
    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.symptomId)
      })
      console.log(ids)
      this.$http.post("/trace/symptom/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getSymptomList()
          }
        });
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {}
      this.dialogFormVisible = false
      this.roleDialogFormVisible = false
    },
    customUpload(file) {
      let FormDatas = new FormData();
      console.log(file);
      FormDatas.append('file', file.file);
      FormDatas.append('name', file.file.name);
      FormDatas.append('size', file.file.size);
      // FormDatas.append('md5', this.md5);
      // var md5 = this.md5;
      // console.log(md5);
      console.log(file)
      this.$http({
        url: '/trace/symptom/upload/' + this.editForm.symptomId,
        method: 'post',
        data: FormDatas,
        //上传进度
        onUploadProgress: (progressEvent) => {
          let num = progressEvent.loaded / progressEvent.total * 100 | 0;  //百分比
          file.onProgress({percent: num})     //进度条
        }
      }).then(data => {
        file.onSuccess(); //上传成功(打钩的小图标)
        this.getSymptomList()
        this.pictureFormVisible = false
      })
    },
    /**     文件正在上传时的钩子    **/
    progressA(event, file) {
    },
    /**     移除上传文件    **/
    handleRemove(file) {
      this.$refs.upload.abort(); //取消上传
      this.$message({message: '成功移除' + file.name, type: 'success'});
    },
    // getMD5(file) {
    //   //console.log(file)
    //   const _this = this
    //   var fileReader = new FileReader();
    //   //此处打印file可看到file下的raw为文件属性
    //   var dataFile = file.raw;
    //   let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
    //   var spark = new SparkMD5.ArrayBuffer();
    //   //获取文件二进制数据
    //   fileReader.readAsArrayBuffer(dataFile)
    //
    //   //异步执行函数
    //   fileReader.onload = function (e) {
    //     spark.append(e.target.result);
    //     var md5 = spark.end()
    //     console.log(md5)
    //     //此处this指向发生改变，需提前声明const _this = this
    //     _this.md5 = md5; //此处是将文件的md5值放入imgdata中
    //     //上传图片，如手动上传可不在此处执行
    //     // _this.upload('frontImg')
    //   }
    // }
  },
  created() {
    this.getSymptomList()
  }
}
</script>
<style scoped>
#user {
  margin: 15px 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
